<?php
/**
 * 
 */
 

function getCommendGames($category, $postnum){
	$cid = get_cat_ID($category);
	
	//改为取该分类下PI值排序的文章
	$commends = get_posts(array('category'=>$cid, 'numberposts'=>$postnum, 'meta_key'=>'GamePI', 'orderby' => 'meta_value_num'));
	
	//$commends = get_posts(array('category'=>$cid, 'numberposts'=>$postnum, 'meta_key'=>'recommend', 'meta_value'=>'是'));
	$result = array();
	foreach ($commends as $key => $commend){
		$temp = array();
		$temp['post_id'] = $commend->ID;
		$temp['post_title'] = $commend->post_title;
		$temp['post_link'] = get_post_permalink($commend->ID);
		$cat = get_the_category($commend->ID);
		$temp['post_category'] = $cat[0]->name;
		$pic = get_post_meta($commend->ID, "GamePic");
		$temp['game_img'] = $pic[0];
		$result[] = $temp;
	}
	
	return $result;
}

function getNewestGames($category, $postnum){
	$commends = get_posts(array('category'=>get_cat_ID($category), 'numberposts'=>$postnum));
	$result = array();
	foreach ($commends as $key => $commend){
		$temp = array();
		$temp['post_id'] = $commend->ID;
		$temp['post_title'] = $commend->post_title;
		$temp['post_link'] = get_post_permalink($commend->ID);
		$cat = get_the_category($commend->ID);
		$temp['post_category'] = $cat[0]->name;
		$pic = get_post_meta($commend->ID, "GamePic");
		$temp['game_img'] = $pic[0];
		$result[] = $temp;
	}
	
	return $result;
}

//获取总浏览量。
function getPostTotalViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '1');
        return "0";
    }
    return $count;
}


//获取文章本周浏览量
function getPostWeeklyViews($postID){
	$weekly_views_key = 'post_weekly_views_count';
	$weekly_count = get_post_meta($postID, $weekly_views_key, true);
	if($weekly_count == ''){
		$today_weekno = date('W');
		delete_post_meta($postID, $weekly_views_key);
    	delete_post_meta($postID, $weekly_views_weekno);
    	add_post_meta($postID, $weekly_views_key, '1');
    	add_post_meta($postID, $weekly_views_weekno, $today_weekno);
    	
    	return '0';
	}
	return $weekly_count;
}


//设置浏览次数，只需在每次single页打开的时候设置即可。
function setPostViews($postID) {
    $total_count_key = 'post_views_count';
    $weekly_views_key = 'post_weekly_views_count';
    
    //记录当前周记录是本年度中的第几周。使用此属性一可使周记录每周清空，二可防止较少打开页面统计错乱。
    $weekly_views_weekno = 'post_weekly_view_weekno'; 
    
    $total_count = get_post_meta($postID, $total_count_key, true);
    
   	//记录总浏览数
    if($total_count==''){
        $total_count = 1;
        delete_post_meta($postID, $total_count_key);
        add_post_meta($postID, $total_count_key, $total_count);
    }else{
        $total_count++;
        update_post_meta($postID, $total_count_key, $total_count);
    }
    
    //记录周浏览量
    $today_weekno = date('W'); //获取本周是本年度的第几周。
    $weekly_count = get_post_meta($postID, $weekly_views_key, true);
    $weekly_weekno = get_post_meta($postID, $weekly_views_weekno, true);
    if($weekly_count =='' || $weekly_weekno == ''){
    	delete_post_meta($postID, $weekly_views_key);
    	delete_post_meta($postID, $weekly_views_weekno);
    	add_post_meta($postID, $weekly_views_key, '1');
    	add_post_meta($postID, $weekly_views_weekno, $today_weekno);
    }else{
    	if ($today_weekno == $today_weekno){ //如果本周与数据库中记录周数相同，则浏览量+1
    		$weekly_count++;
    		update_post_meta($postID, $weekly_views_key, $weekly_count);
    	}else{ //否则清空浏览量，周数更新。
    		update_post_meta($postID, $weekly_views_key, '1');
    		update_post_meta($postID, $weekly_views_key, $today_weekno);
    	}
    }
}

//根据指定的浏览量获取指定数量的文章，获取的文章将根据浏览量的降序排列。类型分为weekly/total
function getPostByViews($viewsType = 'weekly', $postNum = 5){
	$meta_key = 'post_weekly_views_count';
	if ($viewsType == 'weekly'){
		$meta_key = 'post_weekly_views_count';
	}else if($viewsType == 'total'){
		$meta_key = 'post_views_count';
	}
	$args = array('numberposts' => $postNum,'meta_key' =>$meta_key, 'orderby' => 'meta_value_num');
	return get_posts($args);
}


//统计尤其的打开次数
function setGameOpendCount($gameId){
	$game_open_count_key = "post_games_open_count";
	$open_count = get_post_meta($gameId, $game_open_count_key, true);
	if($open_count){
		update_post_meta($gameId, $game_open_count_key, $open_count++);
	}else{
		delete_post_meta($gameId, $game_open_count_key);
		add_post_meta($gameId, $game_open_count_key, 1);
	}
}
/**
 * 获取热门游戏（默认获取10条）
 * @author shiwei 
 * @param $postNum
 * @return unknown_type
 */
function getHotPost( $postNum = 10){
	global $wpdb ;
//	$hotPostQue = "select count(post.post_title) ,post.ID as ID ,post.post_title as post_title ,tax.term_id as term_id ".
//		" from wp_term_taxonomy tax ,wp_term_relationships ships, (select p.* ,m.meta_value meta_value ".
//		" from wp_posts p left join wp_postmeta  m on  m.post_id =  p.ID and m.meta_key='GamePI' and p.post_status = 'publish' ".
//		" AND p.post_type = 'post' ) post where ".
//		" post.ID = ships.object_id and ships.term_taxonomy_id = tax.term_taxonomy_id ".
//		" and tax.taxonomy ='category'  ".
//		" group by post.post_title  order by post.meta_value DESC limit 0,".$postNum;
	
	$hotPostQue = "select  post.ID as ID ,post.post_title as post_title ,post.post_category_name as cat_name ,".
		" post.post_game_image as  GamePic ".
		" from wp_posts post ".
		" where post.post_status = 'publish' and post.post_type = 'post'  ".
		" order by post.post_pi desc limit 0 ,".$postNum;
	$hotposts = $wpdb->get_results($hotPostQue);
	return $hotposts ;
}


//收藏游戏
function collectGame($user_id, $game_id){
	global $wpdb;
	$result = $wpdb->get_results('select ID from wp_usergame where userid='.$user_id.' and gameid='.$game_id.' and type=1');
	if(count($result) == 0)
		$wpdb->insert('wp_usergame', array('userid'=>$user_id, 'gameid'=>$game_id, 'type'=>1, 'created'=>gmdate('Y-m-d H:i:s')));
}

//是否已经收藏过该游戏
function hasCollected($user_id, $game_id){
	global $wpdb;
	$result = $wpdb->get_results('select ID from wp_usergame where userid='.$user_id.' and gameid='.$game_id.' and type=1');
	return count($result);
}


//记录用户打开过的游戏
function noteOpenedGame($user_id, $game_id){
	global $wpdb;
	$result = $wpdb->get_results('select ID from wp_usergame where userid='.$user_id.' and gameid='.$game_id.' and type=0');
	if(count($result) == 0)
		$wpdb->insert('wp_usergame', array('userid'=>$user_id, 'gameid'=>$game_id, 'type'=>0, 'created'=>gmdate('Y-m-d H:i:s')));
}

//获取用户的游戏列表
function getUserGames($userid, $type, $page){
	global $wpdb;
	return $wpdb->get_results('select * from wp_usergame where userid='.$userid.' and type='.$type.' order by created desc limit '.(($page - 1)*15).', '.($page * 15));
}

//获取用户的游戏总数。
function getUserGamesCount($userid, $type){
	global $wpdb;
	$result = $wpdb->get_results('select count(*) as count from wp_usergame where userid='.$userid.' and type='.$type);
	return $result[0]->count;
}

function deleteUserGames($id){
	global $wpdb;
	$wpdb->query('delete from wp_usergame where ID='.$id);
}


/**
 * 根据postID获取游戏的标签id集合
 * @param $game_id
 * @return unknown_type
 */
function findTagByPostId($game_id){
	global $wpdb;
	$tagQuery = "select tax.term_id as term_id , tax.taxonomy as taxonomy from wp_posts post ,wp_term_relationships ships ,wp_term_taxonomy tax ".
		" where post.ID = ships.object_id and ships.term_taxonomy_id = tax.term_taxonomy_id and tax.taxonomy in ('category','post_tag') ". 
		" and post.ID='".$game_id."' " ;
	$tags = $wpdb->get_results($tagQuery);
	
	return $tags ;
}

/**
 * 获取游戏相近的10条游戏（有包含相同的tag个）
 * @author : shiwei 
 * @param $game_id  post id
 * @param $size 查询的条数
 * @return unknown_type
 */
function getRelevancePosts($game_id,$size=10){
	global $wpdb;
	//查询出该游戏的tag+categroy集合
	$tags = findTagByPostId($game_id) ;
	
	//查询tag相关游戏
	$postQuery = " select distinct post.* from wp_posts post ,wp_term_relationships ships ,wp_term_taxonomy tax ".
		" where post.ID = ships.object_id and ships.term_taxonomy_id = tax.term_taxonomy_id and post.post_status = 'publish' AND post.post_type = 'post' ".
		" and post.ID !='".$game_id."' "; 
	
	$condition = "(" ;
	$typeId = "" ;
	foreach ($tags as $tag){
		if("category"==$tag->taxonomy){
			$typeId = $tag->term_id ;
		} else {
			$condition = $condition."'".$tag->term_id."',";
		}
	}
	if($condition!="("){
		$condition = substr($condition,0,strlen($condition)-1);
		$condition = $condition.")" ;
		$postQuery = $postQuery." and ( (tax.term_id in ".$condition." and tax.taxonomy ='post_tag' ) or  " ;
	}else {
		$postQuery = $postQuery." and ( (tax.term_id = '' and tax.taxonomy ='post_tag' ) or  " ;
	}
	$postQuery = $postQuery." ( tax.term_id in ('".$typeId."') and tax.taxonomy ='category')) "  ; 
	$postQuery = $postQuery." order by tax.taxonomy desc limit 0,".$size ;
	$posts = $wpdb->get_results($postQuery);
	return $posts ;
}


//记录用户或游客的访问记录。
function setCustomLog($data){
	global $wpdb;
	$custom_id = $data['custom_id'];
	$results = $wpdb->get_results('select ID,data, op_date from wp_customlog where custom_id="'.$data['custom_id'].'" and data_type='.$data['data_type'].' order by op_date asc');
	if (count($results) >= 5){
		$id = $results[0]->ID;
		if($results[4]->data != $data['data'])
			$wpdb->update('wp_customlog', $data, array('ID'=>$id));
	}else {
		$wpdb->insert('wp_customlog', $data);
	}
}


//获取客户端真实IP
function GetIP(){
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
           $ip = getenv("HTTP_CLIENT_IP");
       else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
           $ip = getenv("HTTP_X_FORWARDED_FOR");
       else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
           $ip = getenv("REMOTE_ADDR");
       else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
           $ip = $_SERVER['REMOTE_ADDR'];
       else
           $ip = "unknown";
   return($ip);
}

//用户登录成功后，判断该机器原来的游客记录和该用户记录，如果已经存在该用户的记录，则删除游客记录，否则将游客记录修改为该用户记录。
function deleteCustomLog($custome_id, $user_id){
	global $wpdb;
	$results = $wpdb->get_results('select count(*) as count from wp_customlog where custom_id="'.$user_id.'"');
	if ($results[0]->count){
		$wpdb->query('delete from wp_customlog where custom_id="'.$custome_id.'"');
	}else{
		$wpdb->update('wp_customlog', array('custom_id' => $user_id), array('custom_id'=>$custome_id));
	}
}

/**
 * 
 * 增加用户的经验值
 * @param  $user_id 要增加的用户ID 
 * @param  $value 要增加的数值。
 */
function addUserEmpiricalValue($user_id, $value){
	$key = "user_empiricalValue";
	$oldvalue = get_user_meta($user_id, $key, true);
	if($oldvalue && $oldvalue != ''){
		$value = $value + (int)$oldvalue;
		update_user_meta($user_id, $key, $value);
	}else{
		delete_user_meta($user_id, $key);
		add_user_meta($user_id, $key, $value);
	}
	
}

/**
 * 获取用户的经验值
 * @param unknown_type $userid
 */
function getUserEmpiricalValue($userid){
	$key = "user_empiricalValue";
	$oldvalue = get_user_meta($userid, $key, true);
	return $oldvalue;
}

/**
 * 
 * 该用户是否打开过此游戏。
 * @param unknown_type $useridm
 * @param unknown_type $gameid
 */
function hasOpendGame($useridm, $gameid){
	global $wpdb;
	$result = $wpdb->get_results('select ID from wp_usergame where userid='.$user_id.' and gameid='.$game_id.' and type=0');
	return count($result) > 0 ? true : false;
}

/**
 * 统计关键词搜索次数
 * @param $keyword 关键词
 * @author shiwei
 * @return unknown_type
 */
function keywordStat($keyword){
	if($keyword!=null && ""!=$keyword){
		global $wpdb;
		$result = $wpdb->query( $wpdb->prepare( "update wp_keyword_stat set find_count = find_count+1 ,post_date = sysdate() where keyword=%s",$keyword ) );
		if($result<1){
			$result = $wpdb->query( $wpdb->prepare( "INSERT INTO wp_keyword_stat( keyword,post_date) VALUES (  %s,sysdate() )",$keyword ) );
		}
	}
}
/**
 * 获取用户玩过的游戏
 * @param $cookid 用户ID唯一标识
 * @author yuyue
 * @return 游戏id,名称
 */
function getWanGuoByCookie($cookid){
	global $wpdb; 
	$return_str = "";
	$result = $wpdb->get_results('select data from wp_customlog where custom_id = \''.$cookid.'\' and data_type = 1 order by op_date desc limit 4 ');
	 
	if(count($result) > 0){
		$youxiID = "";
		foreach($result as $mypost) { 
		  $youxiID .=  $mypost->data.',';  
		} 
		$youxiID = substr($youxiID,0,strlen($youxiID)-1);
		$sql = "select p.id,p.post_title from wp_posts p,wp_customlog c where p.id = c.data and custom_id = '".$cookid."' and data_type = 1 order by op_date desc limit 4";
		$result = $wpdb->get_results($sql);
		$return_str .= '<h4 style="font-weight:normal;width:650px;">最近玩过</h4><script language="javascript" type="text/javascript">';
		foreach($result as $loadimg) {
			$imgurl = get_post_meta ( $loadimg->id, "GamePic", $single = true );
			$return_str .='delayImagPrint.put("'.$loadimg->id.'","'.$imgurl.'");';
			
		}
		$return_str .='</script><ul>';
		foreach($result as $mypost) { 
		 $posttitle = $mypost->post_title;
		  $imgurl = get_post_meta ( $mypost->id, "GamePic", $single = true );
		  
		  $return_str .='<li><a href=?p='.$mypost->id.'><img src="'.$imgurl.'" alt="'.$posttitle.'" width="130" height="101" title="'.$posttitle.'" /></a><img src="http://www.youxisoso.com/wp-content/themes/youxisoso/images/zjwgimgbg.jpg" width="130" height="7" style=" float:left; margin:-5px 0 0 7px" /><a href=?p='.$mypost->id.'>'.$posttitle.'</a></li>';  
		} 
		$return_str .= "</ul>";
		
	}  
  return $return_str;
}




function mytheme_comment($comment, $args, $depth) {
	if($GLOBALS['comment']== null){
		$GLOBALS['comments_indexs'] = ($args['page']-1)* $args['per_page'] +1;
	}else{
		$GLOBALS['comments_indexs'] = $GLOBALS['comments_indexs']+1;
	}
	$GLOBALS['comment'] = $comment; 
?>
	
	<div class="pinglun">
 		<ul class="pl_left">
      		<li><img src="<?php bloginfo('template_url');?>/images/pingltx.jpg" width="57" height="57" alt="评论用户名" title="评论用户名" /></li>
     		<li class="pl_name"><?php echo get_comment_author_link();?></li>
     	</ul>
      	<span class="hengxian"></span>
    	<ul class="pl_cont">
          	<li class="pl_time">发表于:<?php echo get_comment_date() ;echo get_comment_time(); ?></li>
         	<li class="pl_main"><?php comment_text();?></li>
       	</ul>
      	<span class="louceng"><?php echo $GLOBALS['comments_indexs'];?>F</span>
    </div>
	<?php
} 


?>